package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// GroupBuyVerify 团购券核销记录
type GroupBuyVerify struct {
	BaseModel
	GroupBuyActivityId int64   `orm:"column(group_buy_activity_id)" json:"group_buy_activity_id"` // 团购活动ID
	GroupBuyOrderId    int64   `orm:"column(group_buy_order_id)" json:"group_buy_order_id"`       // 团购订单ID
	MemberId           int64   `orm:"column(member_id)" json:"member_id"`                         // 会员ID
	OrderId            int64   `orm:"column(order_id)" json:"order_id"`                           // 订单ID
	OrderNo            string  `orm:"size(50)" json:"order_no"`                                   // 订单号
	StoreId            int64   `orm:"column(store_id)" json:"store_id"`                           // 门店ID
	OperatorId         int64   `orm:"column(operator_id)" json:"operator_id"`                     // 操作员ID
	OrderAmount        float64 `orm:"digits(10);decimals(2)" json:"order_amount"`                 // 订单金额
	VerifyTime         int64   `orm:"" json:"verify_time"`                                        // 核销时间
	VerifyBy           int64   `orm:"" json:"verify_by"`                                          // 核销人
	Remark             string  `orm:"size(255)" json:"remark"`                                    // 备注
}

// TableName 设置表名
func (c *GroupBuyVerify) TableName() string {
	return "ss_group_buy_verify"
}

// CreateGroupBuyVerify 创建团购券核销记录
func CreateGroupBuyVerify(verify *GroupBuyVerify) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(verify)
	return id, err
}

// GetGroupBuyVerifyByOrderId 根据订单ID获取团购券核销记录
func GetGroupBuyVerifyByOrderId(orderId int64) (*GroupBuyVerify, error) {
	o := orm.NewOrm()
	verify := &GroupBuyVerify{OrderId: orderId}
	err := o.Read(verify, "OrderId")
	return verify, err
}

// GetGroupBuyVerifyList 获取团购券核销记录列表
func GetGroupBuyVerifyList(page, pageSize int, filters map[string]interface{}) ([]*GroupBuyVerify, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(GroupBuyVerify))

	// 应用过滤条件
	if memberId, ok := filters["member_id"].(int64); ok && memberId > 0 {
		qs = qs.Filter("member_id", memberId)
	}

	if orderId, ok := filters["order_id"].(int64); ok && orderId > 0 {
		qs = qs.Filter("order_id", orderId)
	}

	if orderNo, ok := filters["order_no"].(string); ok && orderNo != "" {
		qs = qs.Filter("order_no", orderNo)
	}

	if startTime, ok := filters["start_time"].(int64); ok && startTime > 0 {
		qs = qs.Filter("verify_time__gte", startTime)
	}

	if endTime, ok := filters["end_time"].(int64); ok && endTime > 0 {
		qs = qs.Filter("verify_time__lte", endTime)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var verifies []*GroupBuyVerify
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&verifies)

	return verifies, total, err
}

// UpdateGroupBuyVerify 更新团购券核销记录
func UpdateGroupBuyVerify(verify *GroupBuyVerify, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(verify, fields...)
	return err
}

// DeleteGroupBuyVerify 删除团购券核销记录（软删除）
func DeleteGroupBuyVerify(id int64) error {
	o := orm.NewOrm()
	verify := &GroupBuyVerify{BaseModel: BaseModel{Id: id}}
	if err := o.Read(verify); err != nil {
		return err
	}

	verify.IsDeleted = 1
	_, err := o.Update(verify, "IsDeleted")
	return err
}

// VerifyGroupBuyOrder 核销团购券
func VerifyGroupBuyOrder(orderId int64, storeId int64, operatorId int64, remark string) error {
	o := orm.NewOrm()

	// 开始事务
	tx, err := o.Begin()
	if err != nil {
		return err
	}

	// 获取团购订单
	order := &GroupBuyOrder{BaseModel: BaseModel{Id: orderId}}
	if err := o.Read(order); err != nil {
		tx.Rollback()
		return err
	}

	// 更新订单状态为已核销
	order.Status = 2 // 2-已核销
	order.PaidAt = time.Now().Unix()

	_, err = o.Update(order, "Status", "PaidAt")
	if err != nil {
		tx.Rollback()
		return err
	}

	// 创建核销记录
	verify := &GroupBuyVerify{
		GroupBuyActivityId: order.ActivityId,
		GroupBuyOrderId:    order.Id,
		MemberId:           order.MemberId,
		OrderId:            order.Id, // 使用团购订单ID作为订单ID
		OrderNo:            order.OrderNo,
		StoreId:            storeId,
		OperatorId:         operatorId,
		OrderAmount:        float64(order.Amount) / 100,
		VerifyTime:         time.Now().Unix(),
		Remark:             remark,
	}

	// 设置创建和更新信息
	verify.CreatedAt = time.Now().Unix()
	verify.UpdatedAt = time.Now().Unix()

	// 插入核销记录
	_, err = o.Insert(verify)
	if err != nil {
		tx.Rollback()
		return err
	}

	// 提交事务
	return tx.Commit()
}

// GetGroupBuyVerifyById 根据ID获取团购券核销记录
func GetGroupBuyVerifyById(id int64) (*GroupBuyVerify, error) {
	o := orm.NewOrm()
	verify := &GroupBuyVerify{BaseModel: BaseModel{Id: id}}
	err := o.Read(verify)
	return verify, err
}
